using MultiAgentsShared;
using static MultiAgentsClient.Manager.ProjectManager;

namespace MultiAgentsClient.Presentation;

public partial record ProjectSettingsPopupModel
{
    private readonly IEventBus eventBus;

    public IState<bool> IsPopupOpen => State.Value(this, () => false);
    public IState<int> ProjectId => State.Value(this, () => 0);
    public IState<string> ProjectSettings => State.Value(this, () => "");
    
    public ProjectSettingsPopupModel()
    {
        eventBus = EventBus.Instance;

        eventBus.Subscribe<FetchProjectSettingsCompleteCommand>(async cmd => { await OpenProjectSettingsCompletedHandler(cmd); });
    }

    public async Task ClosePopup()
    {
        await IsPopupOpen.SetAsync(false);
    }

    public async Task SaveProjectSettings()
    {
        int projectId = await ProjectId;
        string? projectSettings = await ProjectSettings;
        if (projectSettings == null)
        {
            return;
        }

        eventBus.Publish(new SaveProjectSettingsCommand(projectId, projectSettings));
        await IsPopupOpen.SetAsync(false);
    }

    public async Task DeleteProject()
    {
        int projectId = await ProjectId;

        eventBus.Publish(new DeleteProjectCommand(projectId));
        await IsPopupOpen.SetAsync(false);
    }

    public async ValueTask OpenProjectSettingsCompletedHandler(FetchProjectSettingsCompleteCommand cmd)
    {
        await ProjectSettings.SetAsync(cmd.ProjectSettings);
        await ProjectId.SetAsync(cmd.ProjectId);
        await IsPopupOpen.SetAsync(true);
    }
}
